/**
 * util help class for mas demo
 */
package com.jeecms.paytype.shengpay;

import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import com.jeecms.pay.model.PayResource;

/**
 * @author zhongxiaoguang QQ 10498233
 * 
 */
public class ShengHelper {

	public static ShengPayForm getForm(Map<String, String> paraPool) {
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

		ShengPayForm payForm = new ShengPayForm();
		// 解析请求参数
		payForm.setName("B2CPayment");
		payForm.setVersion("V4.1.1.1.1");
		payForm.setCharset("UTF-8");
		payForm.setMsgSender(PayResource.payclient.getProperty("sheng_msg_sender"));
		payForm.setSendTime(df.format(new Date()));
		payForm.setOrderNo(paraPool.get("OrderNo"));
		payForm.setOrderAmount(paraPool.get("OrderAmount"));
		payForm.setOrderTime(df.format(new Date()));
		payForm.setPayType(paraPool.get("sheng_paytype"));
		payForm.setInstCode("");
		payForm.setPageUrl(paraPool.get("PageUrl"));
		payForm.setNotifyUrl(PayResource.payclient.getProperty("sheng_return_url"));
		payForm.setProductName(paraPool.get("ProductName"));
		payForm.setBuyerContact(paraPool.get("BuyerContact"));
		payForm.setBuyerIp(paraPool.get("BuyerIp"));
		payForm.setExt1(paraPool.get("Ext1"));
		payForm.setSignType("MD5");
		return payForm;

	}

	public static ShengPayForm signForm(ShengPayForm form, String key) {
		String text = form.toSignString();
		String mac = sign(text, key, form.getCharset());
		form.setSignMsg(mac);
		return form;
	}

	private static String sign(String data, String key, String charset) {
		MessageDigest msgDigest = null;
		data = data + key;
		byte[] enbyte = null;
		try {
			msgDigest = MessageDigest.getInstance("MD5");
			msgDigest.update(data.getBytes(charset));
			enbyte = msgDigest.digest();
		} catch (Exception e) {

		}
		return bin2hex(enbyte);
	}

	/**
	 * 字符串转换成十六进制值
	 * 
	 * @param bin
	 *            String 我们看到的要转换成十六进制的字符串
	 * @return
	 */
	public static String bin2hex(byte[] bs) {
		char[] digital = "0123456789ABCDEF".toCharArray();
		StringBuffer sb = new StringBuffer("");
		int bit;
		for (int i = 0; i < bs.length; i++) {
			bit = (bs[i] & 0x0f0) >> 4;
			sb.append(digital[bit]);
			bit = bs[i] & 0x0f;
			sb.append(digital[bit]);
		}
		return sb.toString();
	}
}
